package com.unistec.fileserver.server;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import org.springframework.web.multipart.MultipartFile;

import com.unistec.framework.utils.FileUtils;
import com.unistec.framework.utils.UUIDUtils;

public class TempFile {
	String originalFilename;
	String contentType;
	File file;
	long size;

	public String getOriginalFilename() {
		return originalFilename;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getContentType() {
		return contentType;
	}

	public long getSize() {
		return size;
	}

	public void setSize(long size) {
		this.size = size;
	}

	public InputStream getInputStream() throws Exception {
		return new FileInputStream(this.file);
	}

	public void delete() {
		this.file.delete();
	}

	public static TempFile createTempFile(MultipartFile multipartFile) throws Exception {
		File tempFolder = FileUtils.TempDirectory.location();
		if (!tempFolder.exists()) {
			tempFolder.mkdirs();
		}

		String originalName = multipartFile.getOriginalFilename();
		String extention = FileUtils.getUriExtention(originalName);
		File tempFile = new File(tempFolder, UUIDUtils.get32UUID() + "." + extention);
		org.apache.commons.io.FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), tempFile);

		TempFile uf = new TempFile();
		uf.file = tempFile;
		uf.originalFilename = multipartFile.getOriginalFilename();
		uf.size = multipartFile.getSize();
		uf.contentType = multipartFile.getContentType();
		return uf;
	}

	public void setOriginalFilename(String originalFilename) {
		this.originalFilename = originalFilename;
	}

}
